// 设备播放树
<template>
  <div class="addr-container">
    <el-input placeholder="请输入搜索内容" v-model="left_addr" class="search">
      <i slot="prefix" class="el-input__icon el-icon-search"></i>
    </el-input>

    <el-select v-model="check_group" placeholder="选择公司" @change="handleGroup" class="group-select">
      <el-option v-for="item in list_group" :key="item.id" :label="item.label" :value="item.id"></el-option>
    </el-select>

    <el-cascader class="addr-select" placeholder="选择省市区.街道" :options="list_province" :props="the_props"
      @change="handleNode" filterable></el-cascader>

    <!-- 网点列表 -->
    <div class="branch-list" v-for="item in list_branch" :key="item.id" @click="handleBranch(item.id, item.name)">
      <div class="branch-title" :class="cut_branch.id == item.id ? 'branch-acitive' : ''">
        <span v-if="item.level == 0" class="title">{{ item.name }} [邮政局]</span>
        <span v-if="item.level == 1" class="title">{{ item.provinceName }} [省级]</span>
        <span v-else-if="item.level == 2" class="title">{{ item.cityName }} [市级]</span>
        <span v-else-if="item.level == 3" class="title">{{ item.areaName }} [县区级]</span>
        <span v-else-if="item.level == 4" class="title">{{ item.streetName }} [街道]</span>
        <span>(991/999)</span>
        <i class="el-icon-arrow-right"></i>
      </div>

      <div v-if="Array.isArray(item.list_device)">
        <!-- <div class="device-list" :class="item2.isOnline!=1? 'off-line':'' " v-for="item2 in item.list_device" :key="item2.id" @click.stop="clickNode(item2)">
          <i class="iconfont icon-shipin"></i>
          <span class="device-list-name">{{ item2.name }}</span>
          <i v-if="item2.checked" class="iconfont icon-biaoqiankuozhan_shipin-178 playing"></i>
        </div> -->
        <el-tree :data="item.list_device" :props="defaultProps" @node-click="clickNode"></el-tree>
      </div>
    </div>
  </div>
</template>

<script>
  import waves from "@/directive/waves"; // waves directive
  import {
    parseTime
  } from "@/utils"; // 解析时间
  import {
    getProvinces,
    getCity,
    getArea,
    getStreet,
    getUserAddress,
  } from "@/api/address";
  import {
    branchList,
    deviceList
  } from "@/api/branch";

  import {
    logger
  } from "runjs/lib/common";
  import {
    Message
  } from 'element-ui';
  const calendarTypeOptions = [{
      key: "CN",
      display_name: "China"
    },
    {
      key: "US",
      display_name: "USA"
    },
    {
      key: "JP",
      display_name: "Japan"
    },
    {
      key: "EU",
      display_name: "Eurozone"
    },
  ];

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name;
    return acc;
  }, {});

  export default {
    name: "DeviceTree",
    components: {},
    props: {
      grid_len: { // 宫格数量, 可播放视频数量的上限
        type: [String, Number],
        default: 1,
      },
      model: { // 0直播视频,  1历史视频, 2下载中心
        type: [String, Number],
        default: 0,
      },
      grid_select: { // 当前被选择中的 宫格位置序号
        type: [String, Number],
        default: -1,
      }
    },

    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: "success",
          draft: "info",
          deleted: "danger",
        };
        return statusMap[status];
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type];
      },
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        // if (!validPass(value) && (value && value.length != 64)) {
        if (!validPass(value)) {
          callback(new Error("8~16位,包含大小写字母和数字, 可以有特殊字符"));
        } else {
          callback();
        }
      };

      return {
        // 左侧 tree 区
        left_addr: "", // 左侧地址搜索

        list_province: [], // 省列表
        cut_node: "", // 当前省\市\区 的节点code
        cut_level: "", // 当前节点的等级
        check_group: 11, // 已选的公司
        cut_branch: {
          id: '',
          name: ''
        },
        cut_device: '', // 当前的设备id
        list_group: [{
            id: 11,
            label: "邮政"
          },
          {
            id: 12,
            label: "圆通"
          },
          {
            id: 13,
            label: "申通"
          },
          {
            id: 14,
            label: "中通"
          },
          {
            id: 15,
            label: "韵达"
          },
          {
            id: 16,
            label: "顺丰"
          },
        ],
        list_branch: [], // 网点列表
        defaultProps: {
          children: 'channels',
          label: 'name'
        },

        checkedNodes: new Array(1), // 选中的node集合 ###
        replaceNum: 0, // 替换的视频 宫格位置号 ###

        the_props: {
          // 级联选择器的 配置
          checkStrictly: true, // 父子节点不相互关联
          lazy: true,
          lazyLoad(node, resolve) {
            const {
              level
            } = node;
            if (node.level == 1)
              getCity({
                provinceCode: node.value
              }).then((res) => {
                const list = res.data.map((item, i) => {
                  item.value = item.cityCode;
                  item.label = item.cityName;
                  return item;
                });
                resolve(list);
              });
            else if (node.level == 2)
              getArea({
                cityCode: node.value
              }).then((res) => {
                const list = res.data.map((item, i) => {
                  item.value = item.areaCode;
                  item.label = item.areaName;
                  return item;
                });
                resolve(list);
              });
            else if (node.level == 3)
              getStreet({
                areaCode: node.value
              }).then((res) => {
                const list = res.data.map((item, i) => {
                  item.value = item.streetCode;
                  item.label = item.streetName;
                  return item;
                });
                resolve(list);
              });
            else if (node.level == 4) {
              // this.cut_node = node.value
              // this.cut_level = node.level
            }
          },
        },

      };
    },
    watch: {
      grid_len(newVal, oldVal) { // 监听宫格数量的变化 1, 4, 9, 12, 16, 24
        let remindval = newVal < oldVal ? newVal : oldVal; // 所要保留视频数量的上限
        let resultArr = [];
        if (this.grid_select !== -1) { // 当前有被选中的宫格
          resultArr.push(this.checkedNodes[this.grid_select])
          remindval = remindval - 1;
        }

        if (newVal > oldVal) { // 如果宫格数变大
          for (let i = 0; i < oldVal; i++) {
            if (this.checkedNodes[i] && this.checkedNodes[i].checked && i !== this.grid_select) {
              resultArr.push(this.checkedNodes[i])
            }
          }
        } else { // 宫格数变小
          let count = 0
          for (let i = 0; i < oldVal; i++) {
            if (this.checkedNodes[i] && this.checkedNodes[i].checked && i != this.grid_select && count < remindval) {
              resultArr.push(this.checkedNodes[i])
              count++
            } else if (this.checkedNodes[i] && this.checkedNodes[i].checked && i !== this.grid_select) {
              this.checkedNodes[i].checked = false; // 关闭其余视频??? ###
            }
          }
        }

        this.checkedNodes = new Array(newVal) // 根据宫格数, 更改数组长度

        this.replaceNum = 0;
        this.grid_select = -1;

        for (let i = 0; i < resultArr.length; i++) {
          // this.checkedNodes[i] = resultArr[i];
          this.$set(this.checkedNodes, i, resultArr[i])

          if (resultArr[i]) {
            this.$emit("node-click", resultArr[i], resultArr[i].checked, i); // 打开视频 ??? ###
          }
          // else {
          //   this.$emit('node-click', null, false, i)
          // }
        }
      },

    },
    created() {
      this.getProvinces();
    },
    mounted() {
      this.handleNode(["110000"]); // 默认访问北京这个区域
      this.handleGroup(11); // 默认访问邮政这个公司
    },
    computed: {
      group_name() {
        return (groupId) => {
          if (groupId == 11) return "邮政";
          else if (groupId == 12) return "圆通";
          else if (groupId == 13) return "申通";
          else if (groupId == 14) return "中通";
          else if (groupId == 15) return "韵达";
          else if (groupId == 16) return "顺丰";
        };
      },
    },
    methods: {
      // 切换地点
      handleNode(newval) {
        console.log(newval);
        this.cut_level = newval.length - 1 || 0;
        this.cut_node = newval[newval.length - 1];
        this.getBranchList()
        this.$emit("changenode", newval);
      },

      // 切换公司
      handleGroup(val) {
        this.getBranchList();
        this.$emit("changegroup", val);
      },
      // 获取省份
      getProvinces() {
        getProvinces().then((res) => {
          this.list_province = res.data || []
          this.list_province = this.list_province.map((item, i) => {
            item.value = item.provinceCode;
            item.label = item.provinceName;
            return item;
          })
        });
      },
      // 获取网点列表
      getBranchList() {
        // let temp_query = {pageNo: this.listQuery.page, limit: this.listQuery.limit, groupId: this.listQuery.groupId}
        let temp_query = {
          groupId: this.check_group
        };
        if (this.cut_level == 0) temp_query.provinceCode = this.cut_node;
        else if (this.cut_level == 1) temp_query.cityCode = this.cut_node;
        else if (this.cut_level == 2) temp_query.areaCode = this.cut_node;
        else if (this.cut_level == 3) temp_query.streetCode = this.cut_node;

        branchList(temp_query).then((res) => {
          this.list_branch = res.list || [];
        });
      },
      // 点击某个网点
      handleBranch(id, name) {
        this.cut_branch.id = id;
        this.cut_branch.name = name
        // this.$emit('changebranch',id, name)
        var _list_branch = JSON.parse(JSON.stringify(this.list_branch));

        deviceList({
          cpId: this.cut_branch.id
        }).then((res) => {
          _list_branch.forEach((item, i) => {

            res.data.list.map((item, i) => {
              item.checked = false
              item.branchinfo = this.cut_branch
            })

            if (item.id == this.cut_branch.id && res.data) _list_branch[i].list_device = res.data
              .list // 将请求回来的设备列表, 添加到当前点击的网点
            // if (item.id == this.cut_branch.id && res.data) item.$set()
          })
          this.list_branch = _list_branch
        });
      },
      // 点击某个设备 -------------------------------------------------------------------------------
      clickNode(data, node, page) {
        console.log(data);
        console.log(node)
        console.log(data.checked);
        console.log("查看data:", data);
        this.cut_device = data.id
        // 与历史页面 切换时  展开当前页面
        // let select_arr = []
        // function addParent(node) {   // 获取当前节点的父节点(解决不同页面切换时, 聚焦当前节点的问题)
        //   if(node && node.parent && typeof(node.parent.key)!= 'undefined' && node.parent.key != null) {
        //     select_arr.push(node.parent.key)
        //     addParent(node.parent)
        //   }
        // }
        // addParent(node)
        // if(node.expand) {select_arr.push(node.key)}   // 根据展开与否

        // if(node.level == 3) {   // 点击的是设备, 存上当前节点
        //   this.$store.commit("SAVE_DATA", node)
        // }
        // this.$store.commit("SET_NODE", select_arr)

        // 如下三个变量,页面 暂时未用到
        // this.currLevel = node.level
        // if (node.level === 1) this.currSignal = node.data;   // level == 1
        // if (node.level === 2) this.currChannel = node.data;   // level == 2

        // isOnline分院是否在线, online摄像头设备是否在线
        if (node.level == 1) return
        else if (node.level == 2) {
          // model==1历史模式----------------------------------------
          if (this.model == 1) {
            if (data && data.deviceId && data.status !== 0) { // 有设备id 并且状态值不为 0   (可以将data.deviceId 换成 node.level)
              if (data.checked && page != 'change') { // 被点击的摄像头 正在播放,  则去关闭视频
                this.toggleVideo(0, data, false) // 关闭当前视频
              } else {
                if (this.checkedNodes[0] && page != 'change') {
                  this.toggleVideo(0, this.checkedNodes[0], false) // 关闭原来视频
                }
                this.toggleVideo(0, data, true) // 打开当前视频
              }
            }
          }
          // model==0 直播-----------------------------------------------------
          else if (this.model == 0) {
            if (node.parent.data.isOnline == 1 && data.online == 1) { // 以下是在线视频, 直播状态被点击
              if (data.checked) { // 被点击的摄像头 正在播放,  则去关闭视频
                console.log('被点击的摄像头, 正在播放');
                const position = this.getNodePositionByKey(data.id); // 通过摄像头id 获取到播放该视频的 宫格位置号
                this.toggleVideo(position, data, false) // 关闭当前视频
                // this.toggleVideo(position, undefined, this.checkedNodes[position].data, false)
              } else if (this.grid_select === -1) { // 未处于播放状态,并且无活跃宫格, 找一个位置去播放视频
                console.log('被点击的摄像头, 未处于播放状态, 无活跃宫格');
                const position = this.getInsertPosition();

                this.toggleVideo(position, data, true) // 打开当前视频
              } else { // 未处于播放状态, 在活跃的宫格中 打开视频
                console.log('被点击的摄像头, 未处于播放播放, 有活跃宫格');
                if (this.checkedNodes[this.grid_select] != undefined) { // 活跃的宫格里边有视频, 先关闭原来的
                  this.toggleVideo(this.grid_select, this.checkedNodes[this.grid_select], false) // 关闭原来视频
                }
                this.toggleVideo(this.grid_select, data, true) // 打开视频
              }
            } else {
              this.$message({
                message: "设备不在线",
                type: "warning",
                duration: 4000,
              })
            }
          }
        }
      },

      // 获得一个宫格位置, 用来播放摄像头
      getInsertPosition() {
        let position = -1;
        for (let i = 0; i < this.grid_len; i++) {
          // 如果有空位置，返回第一个空位置作为插入点
          if (position === -1 && this.checkedNodes[i] == undefined) {
            position = i;
            break;
          }
        }
        if (position === -1) { // 没有空位置了，按照replaceNum替换视频
          position = this.replaceNum % this.grid_len;
          this.replaceNum++;
          // 需要将替换  让原来的视频取消播放
          this.toggleVideo(position, this.checkedNodes[position], false) // 关闭原来视频
        }
        return position;
      },
      // 通过摄像头id 获到播放该视频的宫格位置号
      getNodePositionByKey(key) {
        let position = -1;
        for (let i = 0; i < this.grid_len; i++) {
          if (this.checkedNodes[i] && this.checkedNodes[i].id === key) {
            position = i;
            break;
          }
        }
        return position;
      },
      // 父组件通过ref 调用该函数 关闭视频
      closeVideo(position) {
        this.toggleVideo(position, this.checkedNodes[position], this.checkedNodes[position], false)
      },
      // 关闭\打开 视频
      toggleVideo(position, data, toggle) {
        this.$emit("node-click", data, toggle, position);
        data.checked = !data.checked
        if (toggle) this.$set(this.checkedNodes, position, data)
        else {
          this.$set(this.checkedNodes, position, undefined)
        } // ### 关闭视频
      },

      // 过滤: 当前的节点是否显示出来
      filterNode(value, data) {
        if (!value) return true; // 没有索引关键字, 则所有节点都显示
        return data.name.indexOf(value) !== -1; // 有索引关键字,则带关键字的才显示
      },
      // 父组件点击搜索, 会通过ref调用这个函数
      searchTree(val) { // backview.vue文件  通过ref调用了这个函数
        this.$refs.qnTree.filter(val); //filter是el-tree自带的方法 接收一个任意类型的参数，该参数会在 filter-node-method 中作为第一个参数
      },
    },
  };
</script>

<style lang="scss">
  $theme_text: #0f8bfd;
  $backg: rgba(0, 0, 0, 0);
  $deep_text: #5e5e5e;

  $border_color: #d4d4d4;
  $border_light: #d9dada;
  $theme: #00805a;
  $theme_bg: #2b303b;
  $text_light: #9fa1a2;
  $text_middle: #c0c0c0;
  $text_dark: #2b303b;
  $obj_white: #ffffff;

  .crud-input {
    border: 0;

    &.el-input--medium {
      font-size: 12px;
    }

    &.el-input--medium .el-input__inner {
      height: 27px !important;
      background: transparent;
      border: 0;
      -webkit-appearance: none;
      border-radius: 3px;
      // padding: 12px 5px 12px 15px;
      color: $text_dark;
      caret-color: $text_dark;

      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px $backg inset !important;
        -webkit-text-fill-color: $text_dark !important;
      }
    }

    .el-input-group__append {
      color: $theme;
      border: 0;
      border-left: 1px solid $theme;

      .el-button {
        // height: 27px;
        // border: 1px solid $theme !important;
        // background-color: #f11;
      }
    }
  }

  .el-dialog {
    .el-dialog__header {
      background-color: #f5f7f5 !important;
    }
  }

  .formitem-container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .el-form-item {
      width: 49%;
    }
  }
</style>


<style lang="scss" scoped>
  $theme_text: #0f8bfd;
  $backg: rgba(0, 0, 0, 0);
  $deep_text: #5e5e5e;

  $border_color: #d4d4d4;
  $border_light: #d9dada;
  $theme: #00805a;
  $theme_bg: #2b303b;
  $text_light: #9fa1a2;
  $text_middle: #c0c0c0;
  $obj_white: #ffffff;

  .addr-container {
    background-color: #fff;
    padding: 5px;

    .search {
      margin-bottom: 20px;
    }

    .group-select {
      margin-bottom: 20px;
    }

    .addr-select {
      margin-bottom: 20px;
    }

    .branch-list {
      // 网点列表
      cursor: pointer;
      font-size: 13px;
      border-bottom: 1px solid $border_color;

      .branch-title {
        padding: 8px 0;

        // color: $theme;
        .title {
          padding-left: 5px;
          margin-right: 15px;
        }

        .el-icon-arrow-right {
          float: right;
        }

        &.branch-acitive {
          // 正被点击的网点
          background-color: $theme;
          color: $obj_white;
        }
      }

      .device-list {
        padding: 5px 0 5px 20px;
        color: #000;

        &.off-line {
          color: $text_light;
        }
      }

      .device-list-name {
        margin-left: 5px;
      }

      .playing {
        margin-left: 5px;
        font-size: 10px;
        color: $theme;
        font-weight: 600;
      }
    }

  }
</style>
